<!-- ERC-备件管理-备件台账页面 -->
<template>
  <div>
    <div class="equip-wrap-common">
      <div class="equip-tree-wrap">
        <div class="equip-tree-content">
          <px-input v-model="filterText" style="margin-right: 6px" placeholder="请输入关键字搜索" />
          <px-tooltip content="全部收折" placement="top">
            <px-button v-show="isTreeOpen" link type="primary" icon="ChevronUpRectangle" @click="openOrCloseTree('close')" />
          </px-tooltip>
          <px-tooltip content="全部展开" placement="top">
            <px-button v-show="!isTreeOpen" link type="primary" icon="ChevronDownRectangle" @click="openOrCloseTree('open')" />
          </px-tooltip>
          <px-tooltip content="清除选中" placement="top">
            <px-button style="margin-left: 4px" link type="primary" icon="RefreshLeft" @click="resetCheck" />
          </px-tooltip>
        </div>
        <px-scrollbar class="equip-scroll">
          <px-tree
            ref="treeRef"
            :data="treeData"
            :props="{ children: 'children', label: 'name' }"
            :filter-node-method="filterNode"
            node-key="id"
            :expand-on-click-node="false"
            default-expand-all
            highlight-current
            :expanded-keys="expandedKeys"
            @node-click="nodeClick"
          />
        </px-scrollbar>
      </div>
      <div class="equip-table-wrap">
        <px-form class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px">
          <px-row :gutter="16">
            <px-col :span="6">
              <px-form-item label="归属地块">
                <px-select v-model="queryParams.facCode" placeholder="请选择归属地块" filterable clearable @change="queryParams.positionCode = ''">
                  <px-option v-for="item in facCodeList" :key="item.id" :label="item.name" :value="item.value" />
                </px-select>
              </px-form-item>
            </px-col>
            <px-col :span="6">
              <px-form-item label="备件名称">
                <px-input
                  v-model="queryParams.spareName"
                  placeholder="请输入备件名称"
                  maxlength="50"
                  clearable
                  @blur="queryParams.spareName = $event.target.value.trim()"
                  @keyup.enter="queryTable"
                >
                  <template #suffix>
                    <px-icon style="cursor: pointer" @click="queryTable">
                      <search />
                    </px-icon>
                  </template>
                </px-input>
              </px-form-item>
            </px-col>
            <px-col :span="6">
              <px-form-item label="存放位置">
                <px-input
                  v-model="queryParams.positionCode"
                  placeholder="请选择存放位置"
                  maxlength="50"
                  clearable
                  @blur="queryParams.positionCode = $event.target.value.trim()"
                  @keyup.enter="queryTable"
                >
                  <template #suffix>
                    <px-icon style="cursor: pointer" @click="queryTable">
                      <search />
                    </px-icon>
                  </template>
                </px-input>
                <!-- <px-tree-select
                  v-model="queryParams.positionCode"
                  filterable
                  clearable
                  placeholder="请选择存放位置"
                  :props="{
                    children: 'children',
                    label: 'name',
                    value: 'code'
                  }"
                  :data="positionCodeList"
                  :render-after-expand="false"
                  @focus="positionCodeFocus"
                /> -->
              </px-form-item>
            </px-col>
            <px-col :span="6">
              <px-button type="primary" @click="queryTable">查询</px-button>
              <px-button @click="resetTable">重置</px-button>
            </px-col>
          </px-row>
        </px-form>
        <div class="equip-table-btn">
          <px-button v-has="'ERC_SPAREPARTS_LEDGER_ADD'" style="margin-right: 8px" type="primary" :disabled="isEqpTypeCode" @click="addSpareParts"
            >新增备件</px-button
          >
          <px-button v-has="'ERC_SPAREPARTS_LEDGER_DOWNLOADTEMPLATE'" style="margin-right: 8px" type="primary" plain @click="templateDownload"
            >下载模板</px-button
          >
          <BatchUpload
            url="/ifp/erc/api/v1/sparePart/importData"
            title="导入"
            permission="ERC_SPAREPARTS_LEDGER_UPLOAD"
            @updateUploadPage="queryTable"
          />
          <px-button v-has="'ERC_SPAREPARTS_LEDGER_BATCHDOWNLOAD'" style="margin-right: 16px" type="primary" plain @click="batchDownload"
            >批量导出</px-button
          >
          <px-button v-has="'ERC_SPAREPARTS_LEDGER_BATCHDELETE'" type="danger" plain @click="batchDelete">批量删除</px-button>
        </div>
        <px-table
          :data="tableData"
          class="equip-table"
          :row-class-name="setHighlightClass"
          size="small"
          height="calc(100vh - 304px)"
          border
          @selection-change="selectionChange"
        >
          <px-table-column type="selection" width="50" align="center" fixed="left" />
          <px-table-column label="序号" width="80" align="center" fixed="left">
            <template #default="{ $index }">
              {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
            </template>
          </px-table-column>
          <px-table-column
            v-for="(item, index) in tableColumns"
            :key="index"
            :label="item.label"
            :min-width="item.minWidth"
            :align="item.align"
            :show-overflow-tooltip="item.showOverflowTooltip"
            :fixed="item.fixed"
          >
            <template #default="scope">
              {{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}
            </template>
          </px-table-column>
          <px-table-column fixed="right" label="操作" width="100" align="center">
            <template #default="scope">
              <px-tooltip content="编辑" placement="top">
                <px-button v-has="'ERC_SPAREPARTS_LEDGER_EDIT'" link type="primary" icon="EditPen" @click="handleEdit(scope.row)" />
              </px-tooltip>
              <px-tooltip content="删除" placement="top">
                <px-button v-has="'ERC_SPAREPARTS_LEDGER_DELETE'" link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
              </px-tooltip>
            </template>
          </px-table-column>
        </px-table>
        <pagination
          v-show="total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          class="equip-table-pagination"
          :total="total"
          @pagination="queryTable"
        />
      </div>
    </div>
    <!-- 新增/编辑页面 -->
    <AddDialog
      :dialogVisible="dialogVisible"
      :dialogType="dialogType"
      :rowData="rowData"
      :eqpTypeCode="queryParams.eqpTypeCode"
      :eqpTypeCodeDesc="eqpTypeCodeDesc"
      @queryTable="queryTable"
      @closeDialog="dialogVisible = false"
    />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ERC_SPAREPARTS_LEDGER"
});
import { onMounted, reactive, toRefs, watch, getCurrentInstance } from "vue";
import { useRoute } from "vue-router";
import { PxMessage, PxMessageBox } from "px-ui";
import BatchUpload from "@/components/Upload/BatchUpload.vue";
import AddDialog from "./components/AddDialog.vue";
import { queryDictData } from "@/api/common";
import {
  queryEquipTypeTree,
  queryEquipPositionTree,
  querySparePartsLedger,
  deleteSparePartsLedger,
  batchDeleteSparePartsLedger
} from "@/api/erc/spareParts";
const { proxy }: any = getCurrentInstance();

const route = useRoute();
const state = reactive<any>({
  filterText: "",
  treeRef: null,
  treeData: [],
  expandedKeys: [],
  isTreeOpen: true,
  isEqpTypeCode: true,
  facCodeList: [],
  positionCodeList: [],
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    eqpTypeCode: "",
    facCode: "",
    spareName: "",
    positionCode: ""
  },
  tableColumns: [
    { prop: "facCode", label: "归属地块", minWidth: "100", showOverflowTooltip: true, fixed: "left" },
    { prop: "sparePartName", label: "备件名称", minWidth: "160", showOverflowTooltip: true },
    { prop: "eqpTypeCodeDesc", label: "备件类型", minWidth: "160", showOverflowTooltip: true },
    { prop: "brandVal", label: "品牌", minWidth: "100", showOverflowTooltip: true },
    { prop: "specification", label: "规格型号", minWidth: "120", showOverflowTooltip: true },
    { prop: "sparePartUnit", label: "单位", minWidth: "80", showOverflowTooltip: true },
    { prop: "currentStock", label: "库存数量", minWidth: "80", showOverflowTooltip: true },
    { prop: "positionCode", label: "存放位置", minWidth: "140", showOverflowTooltip: true },
    { prop: "safeStock", label: "安全库存", minWidth: "80", showOverflowTooltip: true }
  ],
  tableData: [],
  total: 0,
  selectIds: [],
  dialogVisible: false,
  dialogType: "add",
  rowData: {},
  eqpTypeCodeDesc: ""
});
const {
  filterText,
  treeRef,
  treeData,
  expandedKeys,
  isTreeOpen,
  isEqpTypeCode,
  facCodeList,
  positionCodeList,
  queryParams,
  tableColumns,
  tableData,
  total,
  selectIds,
  dialogVisible,
  dialogType,
  rowData,
  eqpTypeCodeDesc
} = toRefs(state);

// 监视过滤树的值
watch(filterText, val => {
  treeRef.value!.filter(val);
});

// 进入页面时触发
onMounted(() => {
  queryTree();
  querySelectList();
  if (route?.query && route?.query?.spareName) {
    queryParams.value.spareName = route?.query?.spareName;
  }
  queryTable();
});

/** 左侧-树形区 **/
// 查询左侧树
const queryTree = async () => {
  const params = {
    name: ""
  };
  const data: any = await queryEquipTypeTree(params);
  treeData.value = data;
};
// 过滤树数据
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.name.includes(value);
};
// 左侧树添加清除选中按钮
const resetCheck = () => {
  filterText.value = "";
  const selectedNodes = document.querySelectorAll(".is-current");
  selectedNodes.forEach(element => {
    element.classList.remove("is-current");
  });
  queryParams.value.eqpTypeCode = "";
  isEqpTypeCode.value = true;
  queryTable();
};
// 点击左侧树节点，获取facCode，查询设备列表
const nodeClick = e1emData => {
  if (e1emData.code === "0") {
    queryParams.value.eqpTypeCode = "";
  } else {
    queryParams.value.eqpTypeCode = e1emData.code;
  }
  eqpTypeCodeDesc.value = e1emData.name;
  if ((e1emData?.typeLevel === 2 && !e1emData?.children) || e1emData?.typeLevel === 3) {
    isEqpTypeCode.value = false;
  } else {
    isEqpTypeCode.value = true;
  }
  queryTable();
};
// 打开或者关闭树
const openOrCloseTree = type => {
  if (type == "close") {
    isTreeOpen.value = false;
    let nodes = treeRef.value.store._getAllNodes();
    nodes.forEach(item => {
      item.expanded = false;
    });
  } else if (type == "open") {
    isTreeOpen.value = true;
    let nodes = treeRef.value.store._getAllNodes();
    nodes.forEach(item => {
      item.expanded = true;
    });
  }
};

/** 右侧-表格区 **/
// 归属地块下拉框
const querySelectList = async () => {
  facCodeList.value = await queryDictData({ typeCode: "ERC_FACTORY_AREA" });
};
// 存放位置聚焦时
const positionCodeFocus = async () => {
  positionCodeList.value = await queryEquipPositionTree({ facCode: queryParams.value.facCode });
};
// 查询备件台账列表
const queryTable = async () => {
  const params = queryParams.value;
  const data = await querySparePartsLedger(params);
  tableData.value = data?.data;
  total.value = data?.total;
};
// 重置筛选条件和备件台账列表
const resetTable = async () => {
  queryParams.value.facCode = "";
  queryParams.value.spareName = "";
  queryParams.value.positionCode = "";
  queryTable();
};
// 新增备件台账按钮
const addSpareParts = () => {
  dialogType.value = "add";
  dialogVisible.value = true;
};
// 下载模版按钮
const templateDownload = async () => {
  proxy.download("get", "/erc/api/v1/sparePart/templateDownLoad", {}, "备件台账信息模板.xlsx");
};
// 表格多选框选中-批量导出、批量删除使用
const selectionChange = (val: any) => {
  selectIds.value = [];
  val.forEach((item: any) => {
    if (item.id) {
      selectIds.value.push(item.id);
    }
  });
};
// 批量导出按钮
const batchDownload = async () => {
  if (selectIds.value.length == 0) {
    PxMessage.warning("请选择设备后操作");
    return;
  }
  const params = {
    ids: selectIds.value
  };
  proxy.download("post", "/erc/api/v1/sparePart/exportData", params, "备件台账信息.xlsx");
};
// 批量删除按钮
const batchDelete = async () => {
  if (selectIds.value.length == 0) {
    PxMessage.warning("请选择设备后操作");
    return;
  }
  PxMessageBox.confirm(`要删除当前已选的 ${selectIds.value.length} 个备件吗？删除后不可恢复，请谨慎操作`, "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await batchDeleteSparePartsLedger({
        ids: selectIds.value
      });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
// 编辑单条备件台账
const handleEdit = (row: any) => {
  dialogType.value = "edit";
  rowData.value = row;
  dialogVisible.value = true;
};
// 删除单条备件台账
const handleDelete = async (row: any) => {
  PxMessageBox.confirm(`要删除当前备件“${row.sparePartName}”吗？删除后不可恢复，请谨慎操作`, "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await deleteSparePartsLedger({
        id: row.id
      });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
// 设置高亮颜色
const setHighlightClass = ({ row }) => {
  // 根据条件返回不同的类名
  if (row.currentStock === 0 || row.currentStock < row.safeStock) {
    return "highlight-red";
  }
  return "";
};
</script>

<style lang="scss" scoped>
@import url("@/views/erc/scss/table-flex-list.scss");

:deep(.px-table-fixed-column--left) {
  background-color: rgb(231 91 91);
}

:deep(.px-table) {
  .highlight-red {
    background-color: rgb(254 236 236);

    .px-table__cell {
      background-color: rgb(254 236 236) !important;
    }
  }
}
</style>
